package api

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"schedulingsystem/backend/models"
)

// ProductHandler 处理产品相关的API请求
type ProductHandler struct {
	DB *gorm.DB
}

// NewProductHandler 创建一个新的产品处理器
func NewProductHandler(db *gorm.DB) *ProductHandler {
	return &ProductHandler{DB: db}
}

// GetProducts 获取所有产品
func (h *ProductHandler) GetProducts(c *gin.Context) {
	var products []models.Product
	result := h.DB.Find(&products)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取产品列表失败"})
		return
	}

	c.JSON(http.StatusOK, products)
}

// GetProduct 获取单个产品
func (h *ProductHandler) GetProduct(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的产品ID"})
		return
	}

	var product models.Product
	result := h.DB.First(&product, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	c.JSON(http.StatusOK, product)
}

// CreateProduct 创建新产品
func (h *ProductHandler) CreateProduct(c *gin.Context) {
	var product models.Product
	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的产品数据"})
		return
	}

	result := h.DB.Create(&product)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建产品失败"})
		return
	}

	c.JSON(http.StatusCreated, product)
}

// UpdateProduct 更新产品信息
func (h *ProductHandler) UpdateProduct(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的产品ID"})
		return
	}

	var product models.Product
	result := h.DB.First(&product, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	var updatedProduct models.Product
	if err := c.ShouldBindJSON(&updatedProduct); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的产品数据"})
		return
	}

	// 更新字段
	product.Name = updatedProduct.Name
	product.Description = updatedProduct.Description

	result = h.DB.Save(&product)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新产品失败"})
		return
	}

	c.JSON(http.StatusOK, product)
}

// DeleteProduct 删除产品
func (h *ProductHandler) DeleteProduct(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的产品ID"})
		return
	}

	var product models.Product
	result := h.DB.First(&product, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "产品不存在"})
		return
	}

	// 检查是否有班次依赖此产品
	var count int64
	h.DB.Model(&models.Shift{}).Where("product_id = ?", id).Count(&count)
	if count > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无法删除产品，存在依赖的班次记录"})
		return
	}

	result = h.DB.Delete(&product)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除产品失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "产品已删除"})
}
